"use strict";
/**
 * 日志追踪
 * Created by liamjung on 2018/7/2.
 */
const {randomHex} = require("@libfintech/api-gateway-core/util/hex_util");
const TRACE_ID_KEY = global.appConfig.log.traceIdKey;
const SPAN_ID_KEY = global.appConfig.log.spanIdKey;
const PARENT_SPAN_ID_KEY = global.appConfig.log.parentSpanIdKey;

async function main(pipeline, configs) {

    let logTraceId = pipeline.request.headers[TRACE_ID_KEY];
    let logSpanId = pipeline.request.headers[SPAN_ID_KEY];
    let logParentSpanId = pipeline.request.headers[PARENT_SPAN_ID_KEY];

    if (!logTraceId) {

        logTraceId = randomHex();
        logSpanId = logTraceId;

        pipeline.logger.debug("No log trace id, generate new id (value: " + logTraceId + ")");
    } else {

        pipeline.logger.debug("Last log trace id (value: " + logTraceId + ")");
    }

    //当前
    pipeline.logger.traceId = logTraceId;
    pipeline.logger.spanId = logSpanId;
    pipeline.logger.parentSpanId = logParentSpanId;

    //下一环节
    pipeline.request.headers[TRACE_ID_KEY] = logTraceId;
    pipeline.request.headers[SPAN_ID_KEY] = randomHex();
    pipeline.request.headers[PARENT_SPAN_ID_KEY] = logSpanId;
}

module.exports = {
    main: main
};